package com.chengliang.zuoye.config;

import com.chengliang.zuoye.filter.ValidateCodeFilter;
import com.chengliang.zuoye.handler.FailureHandler;
import com.chengliang.zuoye.handler.SuccessHandler;
import com.chengliang.zuoye.service.impl.MyUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private final MyUserDetailsService userDetailsService;

    @Autowired
    private DataSource dataSource;

    @Autowired
    public WebSecurityConfig(MyUserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }


    /**
     * @return
     * 记住我 token注册中心 数据库表的形式存储token
     */
    @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
        tokenRepository.setDataSource(dataSource);
        // 第一次启动的时候自动建表（可以不用这句话，自己手动建表，源码中有语句的）
        //tokenRepository.setCreateTableOnStartup(true);
        return tokenRepository;
    }

    /**
     * @param auth
     * @throws Exception
     * 密码比较
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //自定义验证业务 指定密码对比方式
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //验证失败的处理器
        FailureHandler failureHandler = new FailureHandler();
        //验证码的过滤器
        ValidateCodeFilter validateCodeFilter = new ValidateCodeFilter();
        validateCodeFilter.setAuthenticationFailureHandler(failureHandler);
        http
                // 自定义过滤器，配置到UsernamePasswordAuthenticationFilter之前
                .addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class)
                .authorizeRequests()
                //放行的请求
                .antMatchers("/images/captcha","/user/offline","/user/reg","/user/veremail").permitAll()
                .anyRequest().authenticated()
                .and()
                .rememberMe()                                   // 记住我相关配置
                .tokenRepository(persistentTokenRepository())   // 设置TokenRepository
                // 配置Cookie过期时间 七天免登
                .tokenValiditySeconds(60*60*24*7)
                .and()
                //表单登录
                .formLogin()
                //登录页面路径
                .loginPage("/user/login")
                //登录的请求地址
                .loginProcessingUrl("/login")
                //设置成功的响应处理器
                .successHandler(new SuccessHandler())
                //设置失败的响应处理器
                .failureHandler(failureHandler)
                .permitAll()
                .and()
                //登出
                .logout()
                .permitAll();

        // 关闭CSRF跨域
        http.csrf().disable()
                //允许在相同域名的iframe中显示页面
                .headers().frameOptions().sameOrigin();
        //以下这句就可以控制单个用户只能创建一个session，也就只能在服务器登录一次
        http.sessionManagement().maximumSessions(1).sessionRegistry(sessionRegistry()).expiredUrl("/user/offline");
    }

    @Bean
    public SessionRegistry sessionRegistry(){
        return new SessionRegistryImpl();
    }


    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        //解决静态资源被拦截的问题
        web.ignoring().antMatchers("/layuiadmin/**");
    }


}
